"""
File: wework.py
Author: ershixiong
Date: 2023/12/25
describe:

"""
import json

import requests

from hogwarts.WeworkApi.apis.base_api import BaseApi
from hogwarts.WeworkApi.tests.conftest import global_env
from hogwarts.WeworkApi.utils.utils import Utils


def check_access_token(token_path, base_url):
    """
    检查access_token是否可用，可用返回access_token，不可用返回False
    :param token_path: 相对路径
    :param base_url:
    :return:
    """
    access_token = Utils.get_json_data(token_path).get('access_token')

    # 调用接口，如果失败，说明token失效，需要重新写入token
    url = f'{base_url}department/simplelist'
    params = {
        'access_token': access_token,
    }
    pay_load = {
        'method': 'get',
        'url': url,
        'params': params
    }

    res = requests.request(**pay_load)
    if res.json().get('errcode') == 0:
        return access_token
    else:
        return False


def get_access_token(**kwargs):
    """
    获取token
    :param kwargs:
    :return:
    """
    access_token = check_access_token(kwargs.get('token_path'), kwargs.get('base_url'))
    if not access_token:
        access_token = write_access_token(**kwargs)

    return access_token


def write_access_token(**kwargs):
    """
    :param kwargs:
    :return:
    """
    token_path = kwargs.get('token_path')
    login_path = kwargs.get('login_path')
    base_url = kwargs.get('base_url')
    env = kwargs.get('env')

    yaml_data = Utils.get_yaml_data(f'{login_path}').get(env)

    url = f'{base_url}/gettoken'
    params = {
        'corpid': yaml_data[0][0],
        'corpsecret': yaml_data[0][1],
    }
    pay_load = {
        'method': 'get',
        'url': url,
        'params': params
    }
    res = requests.request(**pay_load)
    access_token = {
        'access_token': res.json().get('access_token')
    }

    access_token_file = Utils.join_path(token_path)
    with open(access_token_file, 'w', encoding='utf-8') as f:
        json.dump(access_token, f)
    return res.json().get('access_token')


def set_base_url(file_path, env):
    """
    :param file_path: 相对路径
    :param env: 根据env获取对应环境的base_url
    :return:
    """

    url_data = Utils.get_yaml_data(file_path)
    return url_data.get(env)[0]


class Wework(BaseApi):
    myenv = global_env.get('env')
    BASE_URL = set_base_url('data/base_url.yaml', myenv)

    kwargs = {
        'token_path': 'data/contacts/contacts_access_token.json',
        'login_path': 'data/contacts/contacts_secret.yaml',
        'base_url': BASE_URL,
        'env': myenv
    }
    ACCESS_TOKEN = get_access_token(**kwargs)
